// utils/api.js - API请求工具类

class API {
  constructor() {
    this.baseUrl = ''
    this.timeout = 10000
  }

  // 设置基础URL
  setBaseUrl(url) {
    this.baseUrl = url
  }

  // 获取完整URL
  getFullUrl(url) {
    if (url.startsWith('http')) {
      return url
    }
    
    const app = getApp()
    const baseUrl = this.baseUrl || (app && app.globalData ? app.globalData.baseUrl : 'https://nzy.congqian.cn/api/')
    return baseUrl + url.replace(/^\//, '')
  }

  // 获取请求头
  getHeaders(needAuth = true) {
    const headers = {
      'Content-Type': 'application/json'
    }

    if (needAuth) {
      const app = getApp()
      const token = (app && app.globalData ? app.globalData.token : null) || wx.getStorageSync('token')
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }
    }

    return headers
  }

  // 处理响应数据
  handleResponse(response) {
    const { data } = response

    // 检查HTTP状态
    if (response.statusCode !== 200) {
      throw new Error(`HTTP ${response.statusCode}: ${response.errMsg}`)
    }

    // 检查业务状态
    if (!data.success && data.code !== 200) {
      // token过期
      if (data.code === 401) {
        const app = getApp()
        if (app && app.clearAuth) {
          app.clearAuth()
        }
        wx.navigateTo({
          url: '/pages/auth/login'
        })
        throw new Error('登录已过期，请重新登录')
      }
      
      throw new Error(data.message || '请求失败')
    }

    return data.data
  }

  // 内部刷新token
  refreshTokenInternal() {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token')
      wx.request({
        url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=refresh-token',
        method: 'POST',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            if (res.data && res.data.success && res.data.data && res.data.data.token) {
              const newToken = res.data.data.token
              const app = getApp()
              if (app && app.globalData) {
                app.globalData.token = newToken
              }
              wx.setStorageSync('token', newToken)
              resolve(newToken)
            } else {
              reject(new Error(res.data?.message || '刷新token失败'))
            }
          } catch (e) {
            reject(new Error('刷新token失败'))
          }
        },
        fail: () => reject(new Error('网络请求失败'))
      })
    })
  }

  // 主要请求方法
  request(options) {
    const {
      url,
      method = 'GET',
      data = {},
      needAuth = true,
      showLoading = false,
      loadingText = '请求中...',
      retryOn401 = true
    } = options

    return new Promise((resolve, reject) => {
      if (showLoading) {
        wx.showLoading({
          title: loadingText,
          mask: true
        })
      }

      wx.request({
        url: this.getFullUrl(url),
        method: method.toUpperCase(),
        data: data,
        header: this.getHeaders(needAuth),
        timeout: this.timeout,
        success: async (response) => {
          try {
            // 优先拦截401，尝试自动刷新一次token并重试
            if (
              response.statusCode === 200 &&
              response.data &&
              response.data.code === 401 &&
              needAuth &&
              retryOn401
            ) {
              try {
                await this.refreshTokenInternal()
                // 使用新token重试一次
                const retryResult = await this.request({
                  url,
                  method,
                  data,
                  needAuth,
                  showLoading,
                  loadingText,
                  retryOn401: false
                })
                resolve(retryResult)
                return
              } catch (e) {
                // 刷新失败则走原有处理
              }
            }

            const result = this.handleResponse(response)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          console.error('API请求失败:', error)
          let message = '网络请求失败'
          
          if (error.errMsg) {
            if (error.errMsg.includes('timeout')) {
              message = '请求超时，请检查网络连接'
            } else if (error.errMsg.includes('fail')) {
              message = '网络连接失败，请检查网络设置'
            }
          }
          
          reject(new Error(message))
        },
        complete: () => {
          if (showLoading) {
            wx.hideLoading()
          }
        }
      })
    })
  }

  // GET请求
  get(url, params = {}, options = {}) {
    // 将params拼接到URL
    if (Object.keys(params).length > 0) {
      const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      
      url += (url.includes('?') ? '&' : '?') + queryString
    }

    return this.request({
      url,
      method: 'GET',
      ...options
    })
  }

  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  // DELETE请求
  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }

  // 上传文件
  uploadFile(options) {
    const {
      url,
      filePath,
      name = 'file',
      formData = {},
      needAuth = true,
      showLoading = true,
      loadingText = '上传中...'
    } = options

    return new Promise((resolve, reject) => {
      if (showLoading) {
        wx.showLoading({
          title: loadingText,
          mask: true
        })
      }

      wx.uploadFile({
        url: this.getFullUrl(url),
        filePath,
        name,
        formData,
        header: this.getHeaders(needAuth),
        success: (response) => {
          try {
            // 解析响应数据
            const data = JSON.parse(response.data)
            if (!data.success && data.code !== 200) {
              throw new Error(data.message || '上传失败')
            }
            resolve(data.data)
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          console.error('文件上传失败:', error)
          reject(new Error('文件上传失败'))
        },
        complete: () => {
          if (showLoading) {
            wx.hideLoading()
          }
        }
      })
    })
  }

  // 批量请求
  async batch(requests) {
    const promises = requests.map(request => this.request(request))
    return Promise.all(promises)
  }
}

// 创建实例
const api = new API()

// 导出常用API方法
export default {
  // 基础方法
  request: api.request.bind(api),
  get: api.get.bind(api),
  post: api.post.bind(api),
  put: api.put.bind(api),
  delete: api.delete.bind(api),
  uploadFile: api.uploadFile.bind(api),
  batch: api.batch.bind(api),

  // 用户认证相关
  auth: {
    // 微信登录
    login: (code) => {
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=login',
          method: 'POST',
          data: { code },
          header: {
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '登录失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取用户信息
    getProfile: () => {
      const token = wx.getStorageSync('token')
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=profile',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取用户信息失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 更新用户信息
    updateProfile: (data) => {
      const token = wx.getStorageSync('token')
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=profile',
          method: 'PUT',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '更新用户信息失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 上传头像
    uploadAvatar: (filePath) => {
      const token = wx.getStorageSync('token')
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=upload-avatar',
          filePath: filePath,
          name: 'avatar',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data && data.success) {
                resolve(data.data)
              } else {
                reject(new Error(data?.message || '头像上传失败'))
              }
            } catch (error) {
              reject(new Error('响应数据解析失败'))
            }
          },
          fail: (error) => {
            reject(new Error('文件上传失败'))
          }
        })
      })
    },
    // 刷新token
    refreshToken: () => {
      const token = wx.getStorageSync('token')
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/user_simple.php?action=refresh-token',
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '刷新token失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    }
  },

  // 内容展示相关
  content: {
    // 获取篇章列表
    getChapters: (params) => api.get('/content.php?action=chapters', params),
    // 获取篇章详情
    getChapter: (id) => api.get('/content.php?action=chapter', { id }),
    // 获取篇章下的展项
    getChapterExhibits: (chapterId, params) => api.get('/content.php?action=chapter_exhibits', { chapter_id: chapterId, ...params }),
    // 获取展项列表
    getExhibits: (params) => api.get('/content.php?action=exhibits', params),
    // 获取展项详情
    getExhibit: (id) => api.get('/content.php?action=exhibit', { id }),
    // 获取展项下的展品
    getExhibitItems: (exhibitId, params) => api.get('/content.php?action=exhibit_items', { exhibit_id: exhibitId, ...params }),
    // 获取展品列表
    getItems: (params) => api.get('/content.php?action=items', params),
    // 获取展品详情
    getItem: (id) => api.get('/content.php?action=item', { id }),
    // 获取多媒体文件
    getMedia: (id) => api.get('/content.php?action=media', { id })
  },

  // 预约相关
  reservation: {
    // 获取可预约时段（个人预约-不需要认证）
    getTimeSlots: (date) => api.get('/miniapp/personal_reservation_final.php?action=timeslots', { date }, { needAuth: false }),
    // 创建个人预约（需要认证）
    create: (data) => api.post('/miniapp/personal_reservation_final.php?action=create', data),
    // 获取个人预约列表（新接口）
    getPersonalList: (params) => api.get('/miniapp/personal_reservation_final.php?action=list', params),
    // 获取个人预约详情
    getPersonalDetail: (id) => api.get('/miniapp/personal_reservation_final.php?action=detail', { id }),
    // 取消个人预约
    cancelPersonal: (id) => api.put('/miniapp/personal_reservation_final.php?action=cancel', {}, { url: `/miniapp/personal_reservation_final.php?action=cancel&id=${id}` }),
    // 团队预约API
    createTeam: (data) => api.post('/miniapp/team_reservation.php?action=create', data),
    getTeamList: (params) => api.get('/miniapp/team_reservation.php?action=list', params),
    getTeamDetail: (id) => api.get('/miniapp/team_reservation.php?action=detail', { id }),
    cancelTeam: (id) => api.put(`/miniapp/team_reservation.php?action=cancel&id=${id}`, {}),
    getTeamStats: () => api.get('/miniapp/team_reservation.php?action=stats'),

    // 获取7天开闭馆排期（不需要认证）
    getSchedule7Days: (startDate, days = 7) => api.get('/schedule.php?action=7days', { start_date: startDate, days }, { needAuth: false })
  },

  // 新增：预约核销相关接口
  verification: {
    // 查询预约（核销员权限）
    query: (reservationCode) => api.get('/verification.php?action=verifier_query', { reservation_code: reservationCode }),
    // 执行核销（核销员权限）
    checkIn: ({ reservation_code, notes = '' }) => api.post('/verification.php?action=verifier_checkin', { reservation_code, notes })
  },

  // 活动相关
  activity: {
    // 返回旧活动接口以兼容旧页面
    getList: (params) => api.get('/activity.php?action=list', params),
    getDetail: (id) => api.get('/activity.php?action=detail', { id }),
    apply: (activityId, data) => api.post(`/activity.php?action=apply&activity_id=${activityId}`, data),
    getMyApplications: (params) => api.get('/activity.php?action=my_applications', params),
    getApplicationDetail: (id) => api.get('/activity.php?action=application_detail', { id }),
    cancelApplication: (id) => api.put('/activity.php?action=cancel', {}, { url: `/activity.php?action=cancel&id=${id}` }),
    getCategories: () => api.get('/activity.php?action=categories'),

    // 新的活动申请API（小程序独立）
    createApplication: (data) => api.post('/miniapp/activity_application.php?action=create', data),
    getApplicationList: (params) => api.get('/miniapp/activity_application.php?action=list', params),
    getApplicationDetailV2: (id) => api.get('/miniapp/activity_application.php?action=detail', { id }),
    cancelApplicationV2: (id) => api.put(`/miniapp/activity_application.php?action=cancel&id=${id}`, {}),
    getApplicationStats: () => api.get('/miniapp/activity_application.php?action=stats'),
    getActivityTypes: () => api.get('/miniapp/activity_application.php?action=types', {}, { needAuth: false })
  },

  // 系统功能相关
  system: {
    // 获取系统配置
    getConfig: () => api.get('/system.php?action=config', {}, { needAuth: false }),
    // 获取闭馆日期
    getClosures: (params) => api.get('/system.php?action=closures', params, { needAuth: false }),
    // 提交志愿者申请
    submitVolunteerApplication: (data) => api.post('/system.php?action=volunteer_apply', data),
    // 获取志愿者申请记录
    getVolunteerApplications: () => api.get('/system.php?action=volunteer_applications'),
    // 提交意见反馈
    submitFeedback: (data) => api.post('/system.php?action=feedback', data),
    // 获取反馈记录
    getFeedback: (params) => api.get('/system.php?action=feedback', params),
    // 获取常见问题
    getFAQ: (params) => api.get('/system.php?action=faq', params, { needAuth: false }),
    // 获取FAQ分类
    getFAQCategories: () => api.get('/system.php?action=faq_categories', {}, { needAuth: false }),
    // 记录访问统计
    recordVisit: (data) => api.post('/system.php?action=visit', data, { showLoading: false })
  },

  // 意见反馈API（按照API文档新增）
  feedback: {
    // 提交意见反馈
    submit: (data) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/feedback.php?action=submit',
          method: 'POST',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '提交失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取意见反馈列表
    getList: (params = {}) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        const queryString = Object.keys(params)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&')
        const url = `https://nzy.congqian.cn/api/miniapp/feedback.php?action=list${queryString ? '&' + queryString : ''}`
        
        wx.request({
          url: url,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取列表失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取意见反馈详情
    getDetail: (id) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/feedback.php?action=detail&id=${id}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取详情失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取反馈类型列表
    getTypes: () => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/feedback.php?action=types',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data.feedback_types)
            } else {
              reject(new Error(res.data?.message || '获取类型失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取意见反馈统计
    getStats: () => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/feedback.php?action=stats',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取统计失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    }
  },

  // 志愿者申请API（按照API文档新增）
  volunteer: {
    // 提交志愿者申请
    apply: (data) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/volunteer.php?action=apply',
          method: 'POST',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '申请失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取志愿者申请列表
    getList: (params = {}) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        const queryString = Object.keys(params)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&')
        const url = `https://nzy.congqian.cn/api/miniapp/volunteer.php?action=list${queryString ? '&' + queryString : ''}`
        
        wx.request({
          url: url,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取列表失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取志愿者申请详情
    getDetail: (id) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/volunteer.php?action=detail&id=${id}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取详情失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 更新志愿者申请信息
    update: (id, data) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/volunteer.php?action=update&id=${id}`,
          method: 'PUT',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '更新失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 撤销志愿者申请
    withdraw: (id) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/volunteer.php?action=withdraw&id=${id}`,
          method: 'DELETE',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '撤销失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    // 获取志愿者申请统计
    getStats: () => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/volunteer.php?action=stats',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取统计失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    }
  },

  // 轮播图相关API
  carousel: {
    // 获取轮播图列表
    getList: () => {
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/carousel_simple.php',
          method: 'GET',
          success: (res) => {
            if (res.statusCode === 200 && res.data.success) {
              resolve(res.data.data.list)
            } else {
              reject(new Error(res.data.message || '获取轮播图失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    }
  },

  // 常用观众信息API
  visitors: {
    // 获取常用观众信息列表
    getList: (params = {}) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        const queryString = Object.keys(params)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&')
        const url = `https://nzy.congqian.cn/api/miniapp/common_visitors.php?action=list${queryString ? '&' + queryString : ''}`
        
        wx.request({
          url: url,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取观众信息失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },

    // 获取常用观众信息详情
    getDetail: (id) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/common_visitors.php?action=detail&id=${id}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '获取详情失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },

    // 创建常用观众信息
    create: (data) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: 'https://nzy.congqian.cn/api/miniapp/common_visitors.php?action=create',
          method: 'POST',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '创建失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },

    // 更新常用观众信息
    update: (id, data) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/common_visitors.php?action=update&id=${id}`,
          method: 'PUT',
          data: data,
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '更新失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    },

    // 删除常用观众信息
    delete: (id) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token')
        wx.request({
          url: `https://nzy.congqian.cn/api/miniapp/common_visitors.php?action=delete&id=${id}`,
          method: 'DELETE',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.success) {
              resolve(res.data.data)
            } else {
              reject(new Error(res.data?.message || '删除失败'))
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'))
          }
        })
      })
    }
  },

  // 订阅消息设置
  subscription: {
    // 获取订阅消息设置
    getSettings: () => api.get('/miniapp/subscribe_settings.php?action=settings'),
    // 更新订阅开关
    update: (enabled) => api.post('/miniapp/subscribe_settings.php?action=update', { subscribe_enabled: enabled })
  },

  // 公告管理
  announcements: {
    // 获取公告列表
    getList: (params = {}) => {
      const queryParams = {
        action: 'list',
        ...params
      }
      const queryString = Object.keys(queryParams)
        .filter(key => queryParams[key] !== undefined && queryParams[key] !== null && queryParams[key] !== '')
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`)
        .join('&')
      return api.get(`/miniapp/announcements.php?${queryString}`)
    },
    
    // 获取公告详情
    getDetail: (id) => {
      return api.get(`/miniapp/announcements.php?action=detail&id=${id}`)
    },
    
    // 获取公告分类
    getCategories: () => {
      return api.get('/miniapp/announcements.php?action=categories')
    },
    
    // 获取热门公告
    getPopular: (params = {}) => {
      const queryParams = {
        action: 'popular',
        ...params
      }
      const queryString = Object.keys(queryParams)
        .filter(key => queryParams[key] !== undefined && queryParams[key] !== null && queryParams[key] !== '')
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`)
        .join('&')
      return api.get(`/miniapp/announcements.php?${queryString}`)
    },
    
    // 点赞/取消点赞
    toggleLike: (id) => {
      return api.post('/miniapp/announcements.php?action=like', { id })
    }
  },

  // 博物馆基础配置相关api
  museum_config: {
    // 获取基础配置，查询的是museum_config表,传参获取指定配置，不传参获取列表
    getList: () => api.get('/miniapp/museum_config.php?action=getList', {}, { needAuth: false }),
  },
}